const fs = require('fs');
const path = require('path');
var tools = require('../../libs/tools');
var config = require(tools.rootPath + 'config');
var { connection, pool, model } = require(tools.rootPath + 'libs/model');

var base = require(tools.controllerPath + 'common/base');
const functions = require(tools.appPath + 'functions');
var md5 = require('md5');

module.exports = class extends base {
  constructor() {
    super();
  }
  index(req, res) {
    this.redirect('/welcome/login');
  }
  async login(req, res) {
    if (await this.session('ADMIN')) {
      this.redirect('/frameset/index');
      return;
    }
    let post = this.post();
    if (this.isPost && Object.keys(post).length > 0) {
      let username = functions.trim(post.username);
      let password = functions.trim(post.password);
      let code = functions.trim(post.code);
      //username && password
      if (!username || !password) {
        this.msg(0, '账号和密码不能为空');
        return;
      }
      //code
      if (!code) {
        this.msg(0, '验证码不能为空');
        return;
      }
      let s = (await this.session('CODE')).toString().toLowerCase();
      if (code.toLowerCase() != s) {
        this.msg(0, '验证码不正确');
        return;
      }
      //username
      let user = await model.find('select * from szh_member where username=?', [username]);
      if (typeof (user['userid']) == 'undefined') {
        this.msg(0, '账号不存在');
        return;
      }
      //group
      if (user.groupid != 1 && user.groupid != 2) {
        this.msg(0, '账号已经被禁用');
        return;
      }
      //密码 123456
      if (md5(password) != user.password) {
        this.msg(0, '密码错误');
        return;
      }
      //save login log
      await model.i("insert into szh_login_back set ?", {
        username: username,
        loginip: this.ip,
        logintime: functions.time(),
        agent: this.userAgent,
      });
      //save session
      delete user.password;
      await this.session('ADMIN', user);
      this.msg(1, '登录成功');
      return;

    }
    return this.tpl();
  }
};
